package com.gdufs.secondhandwebsite.controller;

import com.gdufs.secondhandwebsite.entity.Post;
import com.gdufs.secondhandwebsite.entity.Tag;
import com.gdufs.secondhandwebsite.service.PostService;
import com.gdufs.secondhandwebsite.service.TagPostService;
import com.gdufs.secondhandwebsite.util.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "二手交易网站帖子类相关接口")
@RestController
@RequestMapping("post")
public class PostController extends BaseController{
    @Autowired
    PostService postService;

    @ApiOperation(value = "新建帖子")
    @PostMapping("/create")
    public JsonResult<Long> createPost(@RequestBody Post Post, HttpSession httpSession) {
//        获取当前发布商品的用户id
        String userName = getUsernameFromSession(httpSession);
        String userImg =getUserImgFromSession(httpSession);

       postService.createPost(Post,userName,userImg);
        System.out.println("新增帖子id："+Post.getPostId());
        return new JsonResult<Long>(OK,Post.getPostId());
    }

    @ApiOperation(value = "动态更新帖子内容")
    @PostMapping("/update")
    public JsonResult<Post> updatePost(@RequestBody Post Post){
        boolean is_update =postService.updatePost(Post);
        JsonResult jsonResult = new JsonResult<Post>(OK);
        jsonResult.setData(Post);
        if(is_update){
            jsonResult.setMessage("帖子更新成功");
        }else {
            jsonResult.setMessage("帖子更新失败");
        }
        return jsonResult;
    }

    @ApiOperation(value = "根据帖子Id删除帖子")
    @DeleteMapping("{id}/delete")
    public JsonResult<Void> deleteById(@PathVariable("id") Integer id) {
        // 调用业务对象执行获取数据
        boolean is_del = postService.delPost(id.longValue());
        JsonResult jsonResult = new JsonResult<Post>(OK);
        if(is_del){
            jsonResult.setMessage("帖子删除成功");
        }else {
            jsonResult.setMessage("帖子删除失败");
        }
        return jsonResult;
    }

    @ApiOperation(value = "获取所有帖子")
    @GetMapping("all")
    public JsonResult<List<Post>> getPostAll(){
        List<Post> result =postService.getAllPost();
        JsonResult jsonResult = new JsonResult<List<Post>>(OK);
        jsonResult.setData(result);
        return  jsonResult;
    }

    @ApiOperation(value = "根据帖子Id获取帖子")
    @PostMapping("get_by_id")
    public JsonResult<Post> getById(Long postId) {
        Post result =postService.getPostById(postId);
        JsonResult jsonResult = new JsonResult<Post>(OK);
        jsonResult.setData(result);
        return  jsonResult;
    }
}
